package com.example.demo.intercepter;

import com.example.demo.util.TokenUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");// 取出请求头中的token
        String url = request.getRequestURI();// 获取请求的url,如果是login或者register则不拦截
        //"OPTIONS"是浏览器在发送跨域请求时，会先发送一个OPTIONS请求，用来判断是否可以发送真正的请求
        if ("/user/login".equals(url) || "/OPTIONS".equals(request.getMethod())) {
            return true;// 放行
        } else {
            //判断是否登录
            if (token == null) {
                System.out.println("拦截");
                return false;
            }
            //token验证
            TokenUtil tokenUtil = new TokenUtil();
            if (tokenUtil.verifyToken(token)) {
                return true;

            }
        }
        //token验证失败
        System.out.println("拦截");
        return false;
    }

}
